//
//  GYStoreHomeViewController.m
//  GoodLuck
//
//  Created by apple on 2018/3/12.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

static NSString *storeHomeSecondCellIdentifier = @"storeHomeSecondCellIdentifier";
static NSString *storeHomeFirstCellIdentifier = @"storeHomeFirstCellIdentifier";
static NSString *storeHomeFirstHeadView = @"storeHomeFirstHeadView";
static NSString *storeHomeSecondHeadView = @"storeHomeSecondHeadView";

#import "GYStoreHomeViewController.h"
#import "GYNetWorkTools.h"
#import "GYSearchGoos.h"
#import "GYStoreHomeSecondCell.h"
#import "GYStoreHomeFirstCell.h"
#import "GYStoreHomeFirstHeadView.h"
#import "GYShopHomeViewController.h"

@interface GYStoreHomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

/** 店主推荐数据源 */
@property (nonatomic, strong) NSArray *rec_goods_list;

/** 表格 */
@property (nonatomic, strong) UICollectionView *collectionView;

/** 店铺排行榜的数据源 */
@property (nonatomic, strong) NSArray *goodsRanks;

/** 缓存cell的高度 */
@property (nonatomic, strong) NSMutableDictionary *cachesHeight;
@end

@implementation GYStoreHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化
    [self setupColectionView];
    
    //加载数据
    [self loadStoreInfoData];
    
    //加载店铺排行榜数据
    [self loadStoreGoodsRankData:@"collectdesc"];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.collectionView.frame = self.view.bounds;
}

- (void)setupColectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = 10;
    flowLayout.minimumInteritemSpacing = 10;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.backgroundColor = [UIColor clearColor];
    
    
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    
    //注册cell
    [collectionView registerNib:[UINib nibWithNibName:@"GYStoreHomeSecondCell" bundle:nil] forCellWithReuseIdentifier:storeHomeSecondCellIdentifier];
    [collectionView registerNib:[UINib nibWithNibName:@"GYStoreHomeFirstCell" bundle:nil] forCellWithReuseIdentifier:storeHomeFirstCellIdentifier];
    //注册头视图
    [collectionView registerNib:[UINib nibWithNibName:@"GYStoreHomeFirstHeadView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:storeHomeFirstHeadView];
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:storeHomeSecondHeadView];
}

- (void)loadStoreInfoData {
    //3.加载数据
    [EasyLodingView showLodingText:@"正在加载..."];
    [GYNetWorkTools requestStoreInfo:self.store_id success:^(NSDictionary *obj) {
        //这里设置店铺信息
        //NSLog(@"obj========%@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        NSDictionary *datas = [obj objectForKey:@"datas"];
        if (code == 200) {
            [EasyLodingView hidenLoding];
            NSDictionary *store_info = [datas objectForKey:@"store_info"];
            self.storeInfoCallback(store_info);
            
            //下面加载店主推荐数据
            NSArray *rec_goods_list = [datas objectForKey:@"rec_goods_list"];
            self.rec_goods_list = [GYSearchGoos loadGoodsData:rec_goods_list];
            [self.collectionView reloadData];
        }else if (code == 400) {
            [EasyTextView showText:@"加载数据出错!"];
            [EasyLodingView hidenLoding];
            NSLog(@"网络加载出错======%@",[datas objectForKey:@"error"]);
        }
    } error:^(NSError *error) {
        [EasyTextView showText:@"加载数据出错!"];
        [EasyLodingView hidenLoding];
        NSLog(@"laodStoreInfoFailed====%@",error);
    }];
}

- (void)loadStoreGoodsRankData:(NSString *)ordertype {
     [EasyLodingView showLodingText:@"正在加载..."];
    [GYNetWorkTools requestStoreGoodsRank:self.store_id ordertype:ordertype success:^(NSDictionary *obj) {
        //NSLog(@"obj========%@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        NSDictionary *datas = [obj objectForKey:@"datas"];
        if (code == 200) {
            [EasyLodingView hidenLoding];
            NSArray *goods_list = [datas objectForKey:@"goods_list"];
            
            self.goodsRanks = [GYSearchGoos loadGoodsData:goods_list];
            [self.collectionView reloadData];
            
        }else {
            [EasyTextView showText:@"加载数据出错!"];
            [EasyLodingView hidenLoding];
            NSLog(@"网络加载数据出错...");
        }
    } error:^(NSError *error) {
        [EasyTextView showText:@"加载数据出错!"];
        [EasyLodingView hidenLoding];
        NSLog(@"laodGoodsRankFailed=====%@",error);
    }];
}


#pragma mark -- UICollectionViewDelegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return 1 ;
    }else {
        return self.rec_goods_list.count;
    }
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        GYStoreHomeFirstCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:storeHomeFirstCellIdentifier forIndexPath:indexPath];
        cell.models = self.goodsRanks;
        __weak typeof(self)weakSelf = self;
        cell.shopDetailsViewCallBack = ^(NSInteger tag) {
            
            GYSearchGoos *model = weakSelf.goodsRanks[tag-1];
            GYShopHomeViewController *shopHomeVC = [[GYShopHomeViewController alloc] init];
            shopHomeVC.goods_id = model.goods_id;
            [weakSelf.navigationController pushViewController:shopHomeVC animated:YES];
            };
        
        
        return cell;
    }else {
        GYStoreHomeSecondCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:storeHomeSecondCellIdentifier forIndexPath:indexPath];
        cell.goods = self.rec_goods_list[indexPath.item];
        
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        GYSearchGoos *model = self.rec_goods_list[indexPath.item];
        GYShopHomeViewController *shopHomeVC = [[GYShopHomeViewController alloc] init];
        shopHomeVC.goods_id = model.goods_id;
        [self.navigationController pushViewController:shopHomeVC animated:YES];
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return CGSizeMake(ScreenWidth, (ScreenWidth-10)/2+25);
    }else {
        //GYStoreHomeSecondCell *cell = [[[NSBundle mainBundle]loadNibNamed:@"GYStoreHomeSecondCell" owner:nil options:nil]firstObject];
        GYSearchGoos *model = self.rec_goods_list[indexPath.item];
        CGFloat height = [[self.cachesHeight objectForKey:model.goods_id] floatValue];
        if (height != 0) {
            return CGSizeMake((ScreenWidth-30)/2, height);
        }else {
            //计算cell的高度
            CGFloat nameHeight = [model.goods_name boundingRectWithSize:CGSizeMake((ScreenWidth-30)/2, 999) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size.height;
            CGFloat priceHeight = [[NSString stringWithFormat:@"￥ %@",model.goods_price] boundingRectWithSize:CGSizeMake((ScreenWidth-30)/2, 999) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size.height;
            CGFloat rowHeight = (ScreenWidth-30)/2 + nameHeight+priceHeight+25;
            [self.cachesHeight setObject:@(rowHeight) forKey:model.goods_id];
            
            return CGSizeMake((ScreenWidth-30)/2, rowHeight);
        }
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        if (indexPath.section == 0) {
            GYStoreHomeFirstHeadView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:storeHomeFirstHeadView forIndexPath:indexPath];
            __weak typeof(self) weakSelf = self;
            headView.loadStoreGoodsRankCallBack = ^(NSInteger tag) {
                switch (tag) {
                    case 1:
                    {
                        [weakSelf loadStoreGoodsRankData:@"collectdesc"];
                    }
                        break;
                        
                    case 2:
                    {
                        [weakSelf loadStoreGoodsRankData:@"salenumdesc"];
                    }
                        break;
                        
                    default:
                        break;
                }
            };
            
            return headView;
        }else {
            UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:storeHomeSecondHeadView forIndexPath:indexPath];
            
            headView.backgroundColor = [UIColor whiteColor];
            
            UILabel *lable = [headView viewWithTag:1];
            if (lable == nil) {
                lable = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, ScreenWidth-10, 40)];
                lable.tag = 1;
                lable.font = [UIFont systemFontOfSize:14];
                lable.text = @"店主推荐";
                [headView addSubview:lable];
            }
            
            return headView;
        }
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return CGSizeMake(ScreenWidth, 100);
    }else {
        return CGSizeMake(ScreenWidth, 40);
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, section == 0 ? 0 : 10, section == 0 ? 10 : 0, section == 0 ? 0 : 10);
}


#pragma  mark -- 懒加载

- (NSMutableDictionary *)cachesHeight {
    if (!_cachesHeight) {
        _cachesHeight = [NSMutableDictionary dictionary];
    }
    
    return _cachesHeight;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    self.cachesHeight = nil;
}

- (void)dealloc {
    NSLog(@"GYStoreHomeViewController======dealloc");
}
@end
